# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

from google.protobuf.json_format import ParseDict
from coin.proto.coin_order_gateway_pb2 import OrderGatewayConfig
from coin.strategy.mm.subscription import SubscriptionRequest


def _find_compatible_og_config(sub_key, og_config_dict: dict):
  assert isinstance(og_config_dict, dict), og_config_dict
  for sub_key_str, single_og_config_dict in og_config_dict.items():
    sub_key_in_dict = SubscriptionRequest.from_str(sub_key_str)
    if sub_key.is_compatible(sub_key_in_dict):
      return single_og_config_dict
  return {}


def convert_og_config_from_dict(sub_key: SubscriptionRequest, og_config_dict):
  single_og_config_dict = {}
  if og_config_dict is not None:
    assert isinstance(og_config_dict, dict), og_config_dict
    single_og_config_dict = og_config_dict.get(sub_key.to_str(), None)
    if single_og_config_dict is None:
      single_og_config_dict = _find_compatible_og_config(sub_key, og_config_dict)

  og_config_proto = OrderGatewayConfig()
  ParseDict(single_og_config_dict, og_config_proto, ignore_unknown_fields=True)
  if sub_key.market_type == 'Margin':
    og_config_proto.use_margin_account = True
  return og_config_proto
